from django.db import models
from django.apps import apps
from datetime import datetime, timedelta


class Month(models.Model):
    year = models.IntegerField()
    month = models.IntegerField()
    status = models.TextField(choices=[
        ('approved', 'approved'),
        ('temporary', 'temporary'),
        ('not_approved', 'not_approved')],
        default='not_approved'
    )

    def create_events(self):
        Event = apps.get_model('service.Event')
        User = apps.get_model('users.User')
        start_time = datetime.strptime('01:00', '%H:%M')
        end_time = datetime.strptime('05:00', '%H:%M')
        end_sick_time = datetime.strptime('23:00', '%H:%M')
        for user in User.objects.exclude(is_superuser=True):
            for day in range(1, 32):
                try:
                    weekday = datetime(day=day, month=self.month, year=self.year).weekday()
                except ValueError:
                    continue
                if weekday < 0:
                    Event.objects.create(
                        month=self,
                        kind='work_time',
                        day=day,
                        user=user,
                        start_time=start_time,
                        end_time=end_time
                    )
                    Event.objects.create(
                        month=self,
                        kind='sick',
                        day=day,
                        user=user,
                        start_time=end_time,
                        end_time=end_sick_time
                    )

    def recreate_events(self):
        Event = apps.get_model('users.Event')
        Event.objects.filter(month=self).delete()
        self.create_events()

    @property
    def days_in_month(self):
        return (datetime(self.year, self.month + 1, 1) - datetime(self.year, self.month, 1)).days

    class Meta:
        db_table = "month"
        ordering = ['-year', '-month']

    def __str__(self):
        return f"{self.year} {self.month} {self.status}"


class PredictionFact(models.Model):
    specialization = models.ForeignKey(
        'users.SpecializationType',
        related_name='specialization_fact',
        on_delete=models.CASCADE
    )
    week = models.IntegerField()
    qtty = models.IntegerField(null=True, blank=True)
    qtty_predicted = models.IntegerField(null=True, blank=True)
    month = models.ForeignKey(Month, on_delete=models.CASCADE, related_name='weeks')

    class Meta:
        db_table = "prediction_fact"

    def __str__(self):
        return f"{self.month} {self.week} {self.specialization.specialization} {self.specialization.type} {self.qtty}"
